<template>
  <div class="personal">
    <el-card
      shadow="always"
      :body-style="{ padding: '20px' }"
    >
      <div slot="header">
        <span>用户信息</span>
      </div>
      <div>账号：{{ userInfo.account }}</div>
      <el-divider
        direction="horizontal"
        content-position="left"
      ></el-divider>
      <div>用户组：{{ userInfo.userGroup }}</div>
      <el-divider
        direction="horizontal"
        content-position="left"
      ></el-divider>
      <div>创建时间：{{ userInfo.ctime | dateFmt }}</div>
      <el-divider
        direction="horizontal"
        content-position="left"
      ></el-divider>
      <div>头像：</div>
      <el-divider
        direction="horizontal"
        content-position="left"
      ></el-divider>
      <el-upload
        class="avatar-uploader"
        action="http://sell.h5.itsource.cn:8087/users/avatar_upload"
        :headers="headersObj"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img
          v-if="userInfo.imgUrl"
          :src="userInfo.imgUrl"
          class="avatar"
        />
        <i
          v-else
          class="el-icon-plus avatar-uploader-icon"
        ></i>
      </el-upload>
    </el-card>
  </div>
</template>
<script>
import { avatarEdit } from '@/api/user'
import { mapState } from 'vuex'
import storage from '@/utils/storage.js'
export default {
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo
    }),
    headersObj() {
      return {
        Authorization: 'Bearer ' + storage.getItem('token')
      }
    }
  },
  methods: {
    async handleAvatarSuccess(res, file) {
      // 1. 更新vuex里面的数据
      this.$store.commit('user/SET_USER_INFO', {
        ...this.userInfo,
        ...{ imgUrl: res.imgUrl }
      })
      // 2. 发送请求把数据库中的数据修改
      await avatarEdit(res.imgUrl)
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      // const isLt2M = file.size / 1024 / 1024 < 2
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!')
      // }
      // return isJPG && isLt2M
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
